package com.nuanshui.heatedloan.credit.service.third.party;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nuanshui.framework.lang.DateUtil;
import com.nuanshui.framework.security.DESC;
import com.nuanshui.heatedloan.baseservice.model.UserAgent;
import com.nuanshui.heatedloan.baseservice.service.CommonServiceImpl;
import com.nuanshui.heatedloan.constant.RabbitMqQueue;
import com.nuanshui.heatedloan.constant.ServiceConstant;
import com.nuanshui.heatedloan.credit.constant.*;
import com.nuanshui.heatedloan.credit.facade.*;
import com.nuanshui.heatedloan.credit.facade.third.party.RiskManagerInteractionService;
import com.nuanshui.heatedloan.credit.model.CustomerCreditResult;
import com.nuanshui.heatedloan.credit.model.record.*;
import com.nuanshui.heatedloan.credit.mongodb.*;
import com.nuanshui.heatedloan.credit.request.*;
import com.nuanshui.heatedloan.credit.response.*;
import com.nuanshui.heatedloan.credit.utils.UserAgentUtil;
import com.nuanshui.heatedloan.credit.vo.*;
import com.nuanshui.heatedloan.middleware.rabbitmq.RabbitmqMessageSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by wangxw on 2017/7/21.
 */

@Service(ServiceConstant.RISKMANAGERINTERACTIONSERVICE)
public class RiskManagerInteractionServiceImpl extends CommonServiceImpl
        implements RiskManagerInteractionService {

    private  static  final Logger logger= LoggerFactory.getLogger(RiskManagerInteractionServiceImpl.class);

    public final static String dataType="application/json";


    //公司信息的service
    @Autowired
    private CustomerCompanyInfoService customerCompanyInfoService;
    //个人基本信息
    @Autowired
    private CustomerIdCardInfoService customerIdCardInfoService;
    //人际关系信息
    @Autowired
    private CustomerPeopleRelationshipService customerPeopleRelationshipService;
    //银行卡信息
    @Autowired
    private CustomerBankCardInfoService customerBankCardInfoService;
    //短信信息
    @Autowired
    private SmsUserRecordRepository smsRecordRepository;
    //applist信息
    @Autowired
    private AppRecordRepository appRecordRepository;
    //电话记录
    @Autowired
    private PhoneRecordRepository phoneRecordRepository;
    //设备信息
    @Autowired
    private DeviceRecordRepository deviceRecordRepository;

    @Autowired
    private PayOrderInfoService payOrderInfoService;

    @Autowired
    private CustomerCreditResultService customerCreditResultService;

    @Autowired
    private ContactRecordRepository contactRecordRepository;

    @Autowired
    private RabbitmqMessageSender rabbitmqMessageSender;

    @Value("${credit.risk.url}")
    private String riskUrl;


    private String getRiskUrl(String url)
    {
        return riskUrl+url;
    }

    @Override
    public CalculationLimitResponse calculationLimit(CalculationLimitRequest calculationLimitRequest) {
        HttpStatisticRecord httpStatisticalInfo=new HttpStatisticRecord();  //插入到mobdb的实体类对象
        httpStatisticalInfo.setCreatedTime(new Date());
        CalculationLimitResponse calculationLimitResponse=new CalculationLimitResponse();//返回给调用这个方法的实体类
        String url=getRiskUrl(RiskUrlConstant.CALCULATION_LIMIT_URL);
        httpStatisticalInfo.setUrl(url);
        logger.info("================发送http请求的url为"+url+"===============================");
        calculationLimitRequest.setApplyDate(DateUtil.getToday("yyyy-MM-dd HH:mm:ss")); //申请时间
        this.packageRequestParms(calculationLimitRequest);//封装其他请求参数
        String data= JSON.toJSONString(calculationLimitRequest);
        logger.info("================发送http请求的参数为为"+data+"===============================");
        httpStatisticalInfo.setRequestData(data);
        logger.info("================开始调用风控额度计算接口===============================");
        Map<String,Object> returnValues=com.nuanshui.framework.utils.HttpUtil.postDataReturnData(url,data,dataType);
        logger.info("================调用风控额度计算接口完成===============================");
        int resultCode= (int) returnValues.get("responseCode");
        String resultMessage=(String)returnValues.get("data");
        httpStatisticalInfo.setType(HttpType.HTTPSEND);
        httpStatisticalInfo.setResponseData(resultMessage);
        httpStatisticalInfo.setResultCode(resultCode);
        httpStatisticalInfo.setHttpType(RiskHttpType.CALCULATION_LIMIT);
        httpStatisticalInfo.setUserId(calculationLimitRequest.getCustomerId());
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_HTTP_STATISTIC_RECORE,httpStatisticalInfo,true);
        logger.info("===========http返回的的代码信息为"+resultCode+resultMessage+"==============");
        if(resultCode==200){
            calculationLimitResponse= JSON.parseObject(resultMessage,CalculationLimitResponse.class);
        }else{
            return null;
        }
        //插入mogbd
        return calculationLimitResponse;
    }

    public static void main(String[] args) {
        CalculationLimitResponse applyLoanResponse=new CalculationLimitResponse();
        String data= JSON.toJSONString(applyLoanResponse);
        String url="http://10.1.5.43:8080/credit/auth/callBackCalculationLimit";
        Map<String,Object> returnValues=com.nuanshui.framework.utils.HttpUtil.postDataReturnData(url,data,dataType);
        String resultMessage=(String)returnValues.get("data");
        RiskSelectResponse riskSelectResponse=JSON.parseObject(resultMessage,RiskSelectResponse.class);
        System.out.println("-------------------------665546-----------------------------------------------");

    }

    @Override
    public boolean submitOrder(CalculationLimitRequest calculationLimitRequest) {
        HttpStatisticRecord httpStatisticalInfo=new HttpStatisticRecord();  //插入到mobdb的实体类对象
        httpStatisticalInfo.setCreatedTime(new Date());
        String url=getRiskUrl(RiskUrlConstant.APPLY_ORDER_URL);
        httpStatisticalInfo.setUrl(url);
        calculationLimitRequest.setApplyTime(DateUtil.getToday("yyyy-MM-dd HH:mm:ss"));  //提交订单的申请时间
        CustomerCreditResultVO customerCreditResultVO=customerCreditResultService.
                loadVOByUserId(calculationLimitRequest.getCustomerId());
        String calculateSuccessTime=DateUtil.dateToString(customerCreditResultVO.
                getCalculateSuccessTime(),"yyyy-MM-dd HH:mm:ss");
        calculationLimitRequest.setApplySuccessTime(calculateSuccessTime);
        logger.info("================发送http请求的url为"+url+"===============================");
        this.packageRequestParms(calculationLimitRequest);//封装其他请求参数
        String data= JSON.toJSONString(calculationLimitRequest);
        httpStatisticalInfo.setRequestData(data);
        logger.info("================发送http请求的参数为为"+data+"===============================");
        logger.info("================开始调用风控提交订单接口===============================");
        Map<String,Object> returnValues=com.nuanshui.framework.utils.HttpUtil.postDataReturnData(url,data,dataType);
        logger.info("================调用风控提交订单接口完成===============================");
        int resultCode= (int) returnValues.get("responseCode");
        String resultMessage=(String)returnValues.get("data");
        logger.info("===========http返回的的代码信息为"+resultCode+resultMessage+"==============");
        httpStatisticalInfo.setType(HttpType.HTTPSEND);
        httpStatisticalInfo.setResponseData(resultMessage);
        httpStatisticalInfo.setHttpType(RiskHttpType.APPLY_ORDER);
        httpStatisticalInfo.setUserId(calculationLimitRequest.getCustomerId());
        httpStatisticalInfo.setResultCode(resultCode);
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_HTTP_STATISTIC_RECORE,httpStatisticalInfo,true);
        if(200==resultCode){
            return true;
        }else {
            return false;
        }
    }

    /***
     * 四要素的调用接口
     * @param bankCardRequest
     * @return
     */
    @Override
    public RiskResponse fourFactorVerification (BankCardRequest bankCardRequest){
        HttpStatisticRecord httpStatisticalInfo=new HttpStatisticRecord();  //插入到mobdb的实体类对象
        httpStatisticalInfo.setCreatedTime(new Date());
        httpStatisticalInfo.setHttpType(RiskHttpType.BANK_CARD_VALIDATION);
        httpStatisticalInfo.setUserId(bankCardRequest.getCustomerId());
        RiskResponse riskResponse=new RiskResponse();
        String url=getRiskUrl(RiskUrlConstant.BANK_URL);
        logger.info("============发送http请求的url为"+url+"================");
        httpStatisticalInfo.setUrl(url);
        CustomerIdCardInfoVO customerIdCardInfoVO=customerIdCardInfoService.loadByUserId(bankCardRequest.getCustomerId());
        //姓名
        String customName=customerIdCardInfoVO.getCustomerName();
        //身份证号码
        String customIdCard=customerIdCardInfoVO.getIdCard();
        bankCardRequest.setIdCard(DESC.decrypt3DES(customIdCard));
        bankCardRequest.setCustomerName(customName);
        String data= JSON.toJSONString(bankCardRequest);
        httpStatisticalInfo.setRequestData(data);
        logger.info("================发送http请求的参数为为"+data+"========================");
        Map<String,Object> returnValues=com.nuanshui.framework.utils.HttpUtil.postDataReturnData(url,data,dataType);
        int resultCode= (int) returnValues.get("responseCode");
        String resultMessage=(String)returnValues.get("data");
        logger.info("===============http返回的的代码信息为"+resultCode+resultMessage+"========");
        httpStatisticalInfo.setType(HttpType.HTTPSEND);
        httpStatisticalInfo.setResponseData(resultMessage);
        httpStatisticalInfo.setResultCode(resultCode);
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_HTTP_STATISTIC_RECORE,httpStatisticalInfo,true);
        if(resultCode==200){
            riskResponse=JSON.parseObject(resultMessage,RiskResponse.class);
        }else{
            return null;
        }
        return riskResponse;
    }

    /***
     * 芝麻认证接口
     * @param sesameAuthRequest
     * @return
     */
    public SesameAuthResponse sesameAuth(SesameAuthRequest sesameAuthRequest){
        HttpStatisticRecord httpStatisticalInfo=new HttpStatisticRecord();  //插入到mobdb的实体类对象
        httpStatisticalInfo.setCreatedTime(new Date());
        httpStatisticalInfo.setHttpType(RiskHttpType.ZHI_MA_VALIDATION);
        httpStatisticalInfo.setUserId(sesameAuthRequest.getCustomerId());
        SesameAuthResponse sesameAuthResponse=new SesameAuthResponse();
        String url=getRiskUrl(RiskUrlConstant.ZHI_MA_URL);
        //String url="http://10.1.5.190:8080/frms-auth/zhima/auth";
        httpStatisticalInfo.setUrl(url);
        String data= JSON.toJSONString(sesameAuthRequest);
        httpStatisticalInfo.setRequestData(data);
        logger.info("================发送http请求的参数为为"+data+"=====================");
        logger.info("================开始调用芝麻认证接口===============================");
        Map<String,Object> returnValues=com.nuanshui.framework.utils.HttpUtil.postDataReturnData(url,data,dataType);
        int resultCode= (int) returnValues.get("responseCode");
        String resultMessage=(String)returnValues.get("data");
        logger.info("===========http返回的的代码信息为"+resultCode+resultMessage+"==============");
        httpStatisticalInfo.setType(HttpType.HTTPSEND);
        httpStatisticalInfo.setResponseData(resultMessage);
        httpStatisticalInfo.setResultCode(resultCode);
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_HTTP_STATISTIC_RECORE,httpStatisticalInfo,true);
        if(resultCode==200){
            sesameAuthResponse=JSON.parseObject(resultMessage,SesameAuthResponse.class);
        }else{
            return null;
        }

        return sesameAuthResponse;
    }

    public SelectOperationLogResponse getOperationLog(SelectOperationLogRequest selectOperationLogRequest){
        SelectOperationLogResponse selectOperationLogResponse=new SelectOperationLogResponse();
        HttpStatisticRecord httpStatisticalInfo=new HttpStatisticRecord();  //插入到mobdb的实体类对象
        httpStatisticalInfo.setCreatedTime(new Date());
        httpStatisticalInfo.setHttpType(RiskHttpType.SELECT_OPERATION_LOG);
        httpStatisticalInfo.setUserId(selectOperationLogRequest.getOrderId());
        String url=getRiskUrl(RiskUrlConstant.SELECT_OPERATION_LOG);
        httpStatisticalInfo.setUrl(url);
        String data= JSON.toJSONString(selectOperationLogRequest);
        httpStatisticalInfo.setRequestData(data);
        logger.info("================发送http请求的参数为为"+data+"=====================");
        logger.info("================开始调用查询风控日志接口===============================");
        Map<String,Object> returnValues=com.nuanshui.framework.utils.HttpUtil.postDataReturnData(url,data,dataType);
        int resultCode= (int) returnValues.get("responseCode");
        String resultMessage=(String)returnValues.get("data");
        logger.info("===========http返回的的代码信息为"+resultCode+resultMessage+"==============");
        httpStatisticalInfo.setType(HttpType.HTTPSEND);
        httpStatisticalInfo.setResponseData(resultMessage);
        httpStatisticalInfo.setResultCode(resultCode);
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_HTTP_STATISTIC_RECORE,httpStatisticalInfo,true);
        if(resultCode==200){
            selectOperationLogResponse=JSON.parseObject(resultMessage,SelectOperationLogResponse.class);
        }else{
            return null;
        }
        return selectOperationLogResponse;
    }

    public IsWhiteResponse isWhiteList(IsWhiteRequest isWhiteRequest){
        IsWhiteResponse isWhiteResponse=new IsWhiteResponse();
        HttpStatisticRecord httpStatisticalInfo=new HttpStatisticRecord();  //插入到mobdb的实体类对象
        httpStatisticalInfo.setCreatedTime(new Date());
        String url=getRiskUrl(RiskUrlConstant.WHITELIST);
        httpStatisticalInfo.setUrl(url);
        httpStatisticalInfo.setHttpType(RiskHttpType.WHITELIST);
        httpStatisticalInfo.setUserId(isWhiteRequest.getPhoneNum());
        String data= JSON.toJSONString(isWhiteRequest);
        httpStatisticalInfo.setRequestData(data);
        logger.info("================发送http请求的参数为为"+data+"=====================");
        logger.info("================开始调用查询白名单接口===============================");
        Map<String,Object> returnValues=com.nuanshui.framework.utils.HttpUtil.postDataReturnData(url,data,dataType);
        int resultCode= (int) returnValues.get("responseCode");
        String resultMessage=(String)returnValues.get("data");
        logger.info("===========完成白名单接口调用，返回的的代码信息为"+resultCode+resultMessage+"==============");
        httpStatisticalInfo.setType(HttpType.HTTPSEND);
        httpStatisticalInfo.setResponseData(resultMessage);
        httpStatisticalInfo.setResultCode(resultCode);
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_HTTP_STATISTIC_RECORE,httpStatisticalInfo,true);
        if(resultCode==200){
            isWhiteResponse=JSON.parseObject(resultMessage,IsWhiteResponse.class);
        }else{
            return null;
        }
        return isWhiteResponse;
    }

    public SelectLetterTrialNoteResponse getLetterTrialNote(SelectLetterTrialNoteRequest selectLetterTrialNoteRequest){
        SelectLetterTrialNoteResponse selectLetterTrialNoteResponse=new SelectLetterTrialNoteResponse();
        HttpStatisticRecord httpStatisticalInfo=new HttpStatisticRecord();  //插入到mobdb的实体类对象
        httpStatisticalInfo.setCreatedTime(new Date());
        String url=getRiskUrl(RiskUrlConstant.SELECT_LETTER_TRIAL_NOTE);
        httpStatisticalInfo.setUrl(url);
        httpStatisticalInfo.setHttpType(RiskHttpType.SELECT_LETTER_TRIAL_NOTE);
        httpStatisticalInfo.setUserId(selectLetterTrialNoteRequest.getOrderId());
        String data= JSON.toJSONString(selectLetterTrialNoteRequest);
        httpStatisticalInfo.setRequestData(data);
        logger.info("================发送http请求的参数为为"+data+"=====================");
        logger.info("================开始调用查询风控信审注记接口===============================");
        Map<String,Object> returnValues=com.nuanshui.framework.utils.HttpUtil.postDataReturnData(url,data,dataType);
        int resultCode= (int) returnValues.get("responseCode");
        String resultMessage=(String)returnValues.get("data");
        logger.info("===========http返回的的代码信息为"+resultCode+resultMessage+"==============");
        httpStatisticalInfo.setType(HttpType.HTTPSEND);
        httpStatisticalInfo.setResponseData(resultMessage);
        httpStatisticalInfo.setResultCode(resultCode);
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_HTTP_STATISTIC_RECORE,httpStatisticalInfo,true);
        if(resultCode==200){
            selectLetterTrialNoteResponse=JSON.parseObject(resultMessage,SelectLetterTrialNoteResponse.class);
        }else{
            return null;
        }

        return selectLetterTrialNoteResponse;
    }


    public ClosedDetailedResponse getHistoryCreditAudit(ClosedDetailedRequest closedDetailedRequest){
        ClosedDetailedResponse closedDetailedResponse=new ClosedDetailedResponse();
        HttpStatisticRecord httpStatisticalInfo=new HttpStatisticRecord();  //插入到mobdb的实体类对象
        httpStatisticalInfo.setCreatedTime(new Date());
        String url=getRiskUrl(RiskUrlConstant.SELECT_CLOSED_DETAILED);
        httpStatisticalInfo.setUrl(url);
        httpStatisticalInfo.setHttpType(RiskHttpType.SELECT_CLOSED_DETAILED);
        String data= JSON.toJSONString(closedDetailedRequest);
        httpStatisticalInfo.setRequestData(data);
        logger.info("================发送http请求的参数为为"+data+"=====================");
        logger.info("================开始调用查询风控信审注记接口===============================");
        Map<String,Object> returnValues=com.nuanshui.framework.utils.HttpUtil.postDataReturnData(url,data,dataType);
        int resultCode= (int) returnValues.get("responseCode");
        String resultMessage=(String)returnValues.get("data");
        logger.info("===========http返回的的代码信息为"+resultCode+resultMessage+"==============");
        httpStatisticalInfo.setType(HttpType.HTTPSEND);
        httpStatisticalInfo.setResponseData(resultMessage);
        httpStatisticalInfo.setResultCode(resultCode);
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_HTTP_STATISTIC_RECORE,httpStatisticalInfo,true);
        if(resultCode==200){
            closedDetailedResponse=JSON.parseObject(resultMessage,ClosedDetailedResponse.class);
        }else{
            return null;
        }
        return closedDetailedResponse;
    }

    /***
     * 新增注记信息
     * @param letterTrialNoteRequest
     * @return
     */
    public RiskBaseResponse saveTrialNote(LetterTrialNoteRequest letterTrialNoteRequest){
        RiskBaseResponse riskBaseResponse=new RiskBaseResponse();
        HttpStatisticRecord httpStatisticalInfo=new HttpStatisticRecord();  //插入到mobdb的实体类对象
        httpStatisticalInfo.setCreatedTime(new Date());
        String url=getRiskUrl(RiskUrlConstant.SAVE_LETTER_TRIAL_NOTE);
        httpStatisticalInfo.setUrl(url);
        httpStatisticalInfo.setHttpType(RiskHttpType.SAVE_LETTER_TRIAL_NOTE);
        httpStatisticalInfo.setUserId(letterTrialNoteRequest.getOrderId());
        String data= JSON.toJSONString(letterTrialNoteRequest);
        httpStatisticalInfo.setRequestData(data);
        logger.info("================发送http请求的参数为为"+data+"=====================");
        logger.info("================开始调用查询风控信审注记接口===============================");
        Map<String,Object> returnValues=com.nuanshui.framework.utils.HttpUtil.postDataReturnData(url,data,dataType);
        int resultCode= (int) returnValues.get("responseCode");
        String resultMessage=(String)returnValues.get("data");
        logger.info("===========http返回的的代码信息为"+resultCode+resultMessage+"==============");
        httpStatisticalInfo.setType(HttpType.HTTPSEND);
        httpStatisticalInfo.setResponseData(resultMessage);
        httpStatisticalInfo.setResultCode(resultCode);
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_HTTP_STATISTIC_RECORE,httpStatisticalInfo,true);
        if(resultCode==200){
            riskBaseResponse=JSON.parseObject(resultMessage,RiskBaseResponse.class);
        }else{
            return null;
        }

        return riskBaseResponse;
    }

    /***
     * 新增注记信息
     * @param operationLogRequest
     * @return
     */
    public RiskBaseResponse saveOperationLog( OperationLogRequest operationLogRequest){
        RiskBaseResponse riskBaseResponse=new RiskBaseResponse();
        HttpStatisticRecord httpStatisticalInfo=new HttpStatisticRecord();  //插入到mobdb的实体类对象
        httpStatisticalInfo.setCreatedTime(new Date());
        String url=getRiskUrl(RiskUrlConstant.SAVE_OPERATION_LOG);
        httpStatisticalInfo.setUrl(url);
        httpStatisticalInfo.setHttpType(RiskHttpType.SAVE_OPERATION_LOG);
        httpStatisticalInfo.setUserId(operationLogRequest.getOrderId());
        String data= JSON.toJSONString(operationLogRequest);
        httpStatisticalInfo.setRequestData(data);
        logger.info("================发送http请求的参数为为"+data+"=====================");
        logger.info("================开始调用查询风控信审注记接口===============================");
        Map<String,Object> returnValues=com.nuanshui.framework.utils.HttpUtil.postDataReturnData(url,data,dataType);
        int resultCode= (int) returnValues.get("responseCode");
        String resultMessage=(String)returnValues.get("data");
        logger.info("===========http返回的的代码信息为"+resultCode+resultMessage+"==============");
        httpStatisticalInfo.setType(HttpType.HTTPSEND);
        httpStatisticalInfo.setResponseData(resultMessage);
        httpStatisticalInfo.setResultCode(resultCode);
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_HTTP_STATISTIC_RECORE,httpStatisticalInfo,true);
        if(resultCode==200){
            riskBaseResponse=JSON.parseObject(resultMessage,RiskBaseResponse.class);
        }else{
            return null;
        }
        return riskBaseResponse;
    }


    /***
     * 芝麻认证回调接口
     * @param riskResponse
     */
    public void callBackSesame(RiskResponse riskResponse){
        logger.info("========芝麻认证回调接口插入回调数据开始======");
        logger.info("========芝麻认证回调接口插入回调数据客户的id是===="+riskResponse.getCustomerId()+"==========");
        HttpStatisticRecord httpStatisticalInfo=new HttpStatisticRecord();  //插入到mobdb的实体类对象
        httpStatisticalInfo.setCreatedTime(new Date());
        httpStatisticalInfo.setType(HttpType.HTTPRECEIVE);   //接受的请求
        httpStatisticalInfo.setHttpType(RiskHttpType.ZHI_MA_CALLBACK);
        httpStatisticalInfo.setUserId(riskResponse.getCustomerId());
        String data= JSONObject.toJSONString(riskResponse);
        httpStatisticalInfo.setResponseData(data);
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_HTTP_STATISTIC_RECORE,httpStatisticalInfo,true);
        logger.info("========芝麻认证回调接口插入回调数据完成======");
    }


    /***
     * 查询逾期信息
     * @param riskSelectRequest
     */
    public void selectOverdueInfo(RiskSelectRequest riskSelectRequest,RiskSelectResponse riskSelectResponse){
        logger.info("========查询逾期信息接口插入数据开始======");
        logger.info("========查询逾期信息接口插入数据客户的id是===="+riskSelectRequest.getPhone()+"==========");
        HttpStatisticRecord httpStatisticalInfo=new HttpStatisticRecord();  //插入到mobdb的实体类对象
        httpStatisticalInfo.setCreatedTime(new Date());
        httpStatisticalInfo.setType(HttpType.HTTPRECEIVE);   //接受的请求
        httpStatisticalInfo.setHttpType(RiskHttpType.SELECT_OVERDUE);
        httpStatisticalInfo.setUserId(riskSelectRequest.getPhone());
        String data= JSONObject.toJSONString(riskSelectRequest);
        String responseData=JSONObject.toJSONString(riskSelectResponse);
        httpStatisticalInfo.setResponseData(data);
        httpStatisticalInfo.setRequestData(responseData);
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_HTTP_STATISTIC_RECORE,httpStatisticalInfo,true);
        logger.info("========芝麻认证回调接口插入数据完成======");
    }

    /***
     * 计算额度接口回调
     * @param calculationLimitResponse
     */
    public void callBackCalculationLimit(CalculationLimitResponse calculationLimitResponse){
        logger.info("========计算额度回调接口插入回调数据开始======");
        logger.info("========计算额度回调接口插入回调数据客户的id是===="+calculationLimitResponse.getCustomerId()+"==========");
        HttpStatisticRecord httpStatisticalInfo=new HttpStatisticRecord();  //插入到mobdb的实体类对象
        httpStatisticalInfo.setCreatedTime(new Date());
        httpStatisticalInfo.setType(HttpType.HTTPRECEIVE);   //接受的请求
        httpStatisticalInfo.setHttpType(RiskHttpType.CALCULATION_LIMIT_CALLBACK);
        httpStatisticalInfo.setUserId(calculationLimitResponse.getCustomerId());
        String data= JSONObject.toJSONString(calculationLimitResponse);
        httpStatisticalInfo.setResponseData(data);
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_HTTP_STATISTIC_RECORE,httpStatisticalInfo,true);
        logger.info("========计算额度回调接口插入回调数据完成======");
    }




    /***
     * 贷款申请通过回掉接口
     * @param applyLoanResponse
     */
    public void  callBackSubmitOrder(ApplyLoanResponse applyLoanResponse){
        logger.info("========贷款申请回调接口插入回调数据开始======");
        logger.info("========贷款申请回调接口插入回调数据客户的id是===="+applyLoanResponse.getCustomerId()+"==========");
        HttpStatisticRecord httpStatisticalInfo=new HttpStatisticRecord();  //插入到mobdb的实体类对象
        httpStatisticalInfo.setCreatedTime(new Date());
        httpStatisticalInfo.setType(HttpType.HTTPRECEIVE);   //接受的请求
        httpStatisticalInfo.setHttpType(RiskHttpType.APPLY_ORDER_CALLBACK);
        httpStatisticalInfo.setUserId(applyLoanResponse.getCustomerId());
        String data= JSONObject.toJSONString(applyLoanResponse);
        httpStatisticalInfo.setResponseData(data);
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_HTTP_STATISTIC_RECORE,httpStatisticalInfo,true);
        logger.info("========贷款申请回调接口插入回调数据开始======");
    }

    /***
     * 提额通过回掉接口
     * @param raiseLimitResponse
     */
    public void callBackRaiseLimit(RaiseLimitResponse raiseLimitResponse){
        HttpStatisticRecord httpStatisticalInfo=new HttpStatisticRecord();  //插入到mobdb的实体类对象
        httpStatisticalInfo.setCreatedTime(new Date());
        httpStatisticalInfo.setType(HttpType.HTTPRECEIVE);   //接受的请求
        String data= JSONObject.toJSONString(raiseLimitResponse);
        httpStatisticalInfo.setRequestData(data);
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_HTTP_STATISTIC_RECORE,httpStatisticalInfo,true);
    }


    /***
     * 提额接口
     * @param raiseLimitRequest
     * raiseLimitRequest 里面就是其实就是传一个订单的id和客户的id,贷款的类型  期数
     */
    @Override
    public void raiseLimit(RaiseLimitRequest raiseLimitRequest) {
        HttpStatisticRecord httpStatisticalInfo=new HttpStatisticRecord();  //插入到mobdb的实体类对象
        httpStatisticalInfo.setCreatedTime(new Date());
        String url=getRiskUrl(RiskUrlConstant.UPAMT_URL);
        httpStatisticalInfo.setUrl(url);
        this.dealOrderParams(raiseLimitRequest);
        String data= JSON.toJSONString(raiseLimitRequest);
        httpStatisticalInfo.setRequestData(data);
        logger.info("================开始调用风控提额接口===============================");
        Map<String,Object> returnValues=com.nuanshui.framework.utils.HttpUtil.postDataReturnData(url,data,dataType);
        int resultCode= (int) returnValues.get("responseCode");
        String resultMessage=(String)returnValues.get("data");
        logger.info("================开始调用风控提额接口===============================");
        logger.info("===========http返回的的代码信息为"+resultCode+resultMessage+"==============");
        httpStatisticalInfo.setType(HttpType.HTTPSEND);
        httpStatisticalInfo.setResponseData(resultMessage);
        httpStatisticalInfo.setResultCode(resultCode);
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_HTTP_STATISTIC_RECORE,httpStatisticalInfo,true);
    }

    /***
     * 芝麻分数查询接口
     * @param selectSesameRequest
     * @return
     */
    @Override
    public SelectSesameResponse selectSesameInfo(SelectSesameRequest selectSesameRequest){
        SelectSesameResponse selectSesameResponse=new SelectSesameResponse();
        HttpStatisticRecord httpStatisticalInfo=new HttpStatisticRecord();  //插入到mobdb的实体类对象
        httpStatisticalInfo.setCreatedTime(new Date());
        String url=getRiskUrl(RiskUrlConstant.SELECT_SESAME_INFO);
        httpStatisticalInfo.setUrl(url);
        httpStatisticalInfo.setHttpType(RiskHttpType.SELECT_SESAME);
        httpStatisticalInfo.setUserId(selectSesameRequest.getCustomerId());
        String data= JSON.toJSONString(selectSesameRequest);
        httpStatisticalInfo.setRequestData(data);
        logger.info("================开始调用风控芝麻分数查询接口===============================");
        Map<String,Object> returnValues=com.nuanshui.framework.utils.HttpUtil.postDataReturnData(url,data,dataType);
        int resultCode= (int) returnValues.get("responseCode");
        String resultMessage=(String)returnValues.get("data");
        logger.info("================调用风控芝麻分数查询接口完成===============================");
        httpStatisticalInfo.setType(HttpType.HTTPSEND);
        httpStatisticalInfo.setResponseData(resultMessage);
        httpStatisticalInfo.setResultCode(resultCode);
        rabbitmqMessageSender.send(RabbitMqQueue.RABBIT_MQ_HTTP_STATISTIC_RECORE,httpStatisticalInfo,true);
        if(resultCode==200){
            selectSesameResponse=JSON.parseObject(resultMessage,SelectSesameResponse.class);
        }else{
            return null;
        }
        return selectSesameResponse;
    }


    /***
     * 提额接口参数的封装
     * @param raiseLimitRequest
     */
   private void dealOrderParams(RaiseLimitRequest raiseLimitRequest){
        //查找额度表
       CustomerCreditResult customerCreditResult=new CustomerCreditResult();
       customerCreditResult =customerCreditResultService.loadVOByUserId(raiseLimitRequest.getCustomerId());
     //查询所以的历史订单而且创建时间升序排序
       List<PayOrderInfoVO> payOrderInfoVOs=new ArrayList<PayOrderInfoVO>();
       List<Integer> statuss=new ArrayList<Integer>();
       statuss.add(1);
       List<Integer> types=new ArrayList<Integer>();
       types.add(1);
       payOrderInfoVOs= payOrderInfoService.loadVOByUserIdByTypeByStatus(raiseLimitRequest.getCustomerId(),statuss,types);
       List<BorrowHistory> borrowHistorys=new ArrayList<BorrowHistory>();
       BorrowHistory borrowHistory=new BorrowHistory();
       for(int i=0;i<payOrderInfoVOs.size();i++ ){
           PayOrderInfoVO payOrderInfoVO=payOrderInfoVOs.get(i);
           borrowHistory.setLoanTimes((i+1)+"");  //续待次数
           int overdueDay= payOrderInfoVO.getOverdueDays();
           if(overdueDay>0){
               borrowHistory.setIsOverdue("2");  //已经逾期
               borrowHistory.setOverdueDay(overdueDay+"");//逾期天数
           }else{
               borrowHistory.setIsOverdue("1");  //没有逾期
               borrowHistory.setOverdueDay("0");//逾期天数
           }
           borrowHistory.setBorrowTime
                   (DateUtil.dateToString(payOrderInfoVO.getReturnTime(),"yyyy-MM-dd hh:mm:ss"));  //还款时间
           borrowHistory.setBorrowDay(payOrderInfoVO.getLoadDays()+""); //贷款天数
           borrowHistory.setOrderId(payOrderInfoVO.getOrderNo());  //订单号
           borrowHistory.setBeforeDay(payOrderInfoVO.getBorrowType()+"");
           Date date=payOrderInfoVO.getReturnTime();
           int dayNum=DateUtil.dateNum(Calendar.getInstance().getTime(),date);
           borrowHistory.setBeforeDay((dayNum>0?dayNum:0)+"");//提前还款天数
           borrowHistorys.add(borrowHistory);
       }
       raiseLimitRequest.setBorrowHistorys(borrowHistorys);
       //剩余金额
       List<Integer> statusAmt=new ArrayList<Integer>();
       statusAmt.add(2);
       List<Integer> typeAmt=new ArrayList<Integer>();
       typeAmt.add(2);
       Integer loanAmt=payOrderInfoService.getSumAmtByUserIdByTypeByStatus(raiseLimitRequest.getCustomerId(),statusAmt,typeAmt);
       if(loanAmt==null){
           loanAmt=0;
       }
       //剩余金额
       int singleAmt=customerCreditResult.getSingleAmt();
       int installAmt=customerCreditResult.getInstallmentAmt();
       int allAmt=customerCreditResult.getTotalAmt();
       int remainAmt=0;
       //单期贷
       if(Integer.parseInt(raiseLimitRequest.getBorrowType())== BorrowType.SINGLELOAN){
           remainAmt=(singleAmt-loanAmt)<allAmt?(singleAmt-singleAmt):allAmt;
        }else if(Integer.parseInt(raiseLimitRequest.getBorrowType())== BorrowType.INSTALLMENT){
           remainAmt=(installAmt-loanAmt)<allAmt?(installAmt-singleAmt):allAmt;
       }
       raiseLimitRequest.setLeftAmt(remainAmt+"");
   }

    /***
     * 计算额度和提交订单接口参数的封装
     * @param calculationLimitRequest
     * @return
     */
    private  CalculationLimitRequest packageRequestParms(CalculationLimitRequest calculationLimitRequest){
        UserAgent userAgent=this.getUserAgent();
        //公司信息
        CustomerCompanyInfoVO customerCompanyInfoVO=customerCompanyInfoService.loadVOByUserId(calculationLimitRequest.getCustomerId());
        //基本信息
        CustomerIdCardInfoVO customerIdCardInfoVO=customerIdCardInfoService.loadByUserId(calculationLimitRequest.getCustomerId());
        //人员关系
        List<CustomerPeopleRelationshipVO> customerPeopleRelationshipVOs=customerPeopleRelationshipService.
                loadcustomerPeopleRelationshipVOByCusId(calculationLimitRequest.getCustomerId());
        //银行卡
        List<CustomerBankCardInfoVO> customerBankCardInfoVOs=customerBankCardInfoService.loadCustomerBankCardInfoVOByUserId(calculationLimitRequest.getCustomerId());
        calculationLimitRequest.setRelationInfo(customerPeopleRelationshipVOs);
        calculationLimitRequest.setCompanyInfo(customerCompanyInfoVO);
        IdCardInfo idCardInfo=calculationLimitRequest.getIdCardInfo();
        idCardInfo.setCustomerAddress(customerIdCardInfoVO.getAddress());  //设置人员信息的客户的地址
        idCardInfo.setMaritalStatus(customerIdCardInfoVO.getMarriageCondition());  //设置人员信息的婚姻状态
        String idCard=DESC.decrypt3DES(customerIdCardInfoVO.getIdCard());
        idCardInfo.setSex(customerIdCardInfoVO.getSex()+"");   //设置性别    1  男  2  女  3  未知
        idCardInfo.setAge(customerIdCardInfoVO.getAge()+"");   //设置年龄
        List<BankCardInfo> cardNo=new ArrayList<BankCardInfo>();
        for(CustomerBankCardInfoVO customerBankCardInfoVO:customerBankCardInfoVOs){
            BankCardInfo bankCardInfo=new BankCardInfo();
            bankCardInfo.setBankCardNum(DESC.decrypt3DES(customerBankCardInfoVO.getMixCardNo()));
            bankCardInfo.setBankCode(customerBankCardInfoVO.getCardBankCode());
            cardNo.add(bankCardInfo);
        }
        idCardInfo.setBankCardInfo(cardNo);  //设置卡号
        idCardInfo.setCustomerIdCard(idCard);  //设置身份证号
        idCardInfo.setCustomerName(customerIdCardInfoVO.getCustomerName());
        calculationLimitRequest.setIdCardInfo(idCardInfo);
        //设置渠道数据
        String clientType=UserAgentUtil.getClient(userAgent);
        if(clientType.equals(ClientType.IOS)||clientType.equals(ClientType.ANDROID)){
            calculationLimitRequest.setLoanChannel(ClientType.APP);
        }else if(clientType.equals(clientType.equals(ClientType.H5))){
            calculationLimitRequest.setLoanChannel(ClientType.H5);
        }
        calculationLimitRequest.setNewOldSigns(payOrderInfoService.isnewOldSigns(calculationLimitRequest.getCustomerId()));
        this.setPhoneInfo(calculationLimitRequest,clientType);
        return calculationLimitRequest;
    }

    private void setPhoneInfo(CalculationLimitRequest calculationLimitRequest,String clientType){
        //封装通讯录
        List<ContactRecord> contactRecords
        =contactRecordRepository.findByUserId(calculationLimitRequest.getCustomerId());
        for(ContactRecord contactRecord:contactRecords){
          String mixName=contactRecord.getName();
          String mixPhone=contactRecord.getPhone();
          contactRecord.setName(DESC.decrypt3DES(mixName));
            contactRecord.setPhone(DESC.decrypt3DES(mixPhone));
        }
        calculationLimitRequest.setAddressList(contactRecords);
        //封装通话记录
        List<PhoneRecord> phoneRecords=phoneRecordRepository.findByUserId(calculationLimitRequest.getCustomerId());
        calculationLimitRequest.setCallLog(phoneRecords);
        if(phoneRecords!=null&&phoneRecords.size()>0){
            calculationLimitRequest.setIsCallInfo(AuthStatisticsConstant.NORMALTRANSMISSION);
        }else{
            if(ClientType.IOS.equals(clientType)){
                calculationLimitRequest.setIsCallInfo(AuthStatisticsConstant.CANNOTREAD);
            }else{
                calculationLimitRequest.setIsCallInfo(AuthStatisticsConstant.READWITHOUTPERMISSION);
            }
        }
        //短信内容
        List<SmsRecord> smsRecord=smsRecordRepository.findByUserId(calculationLimitRequest.getCustomerId());
        calculationLimitRequest.setMessageList(smsRecord);
        if(smsRecord!=null&&phoneRecords.size()>0){
            calculationLimitRequest.setIsMessageList(AuthStatisticsConstant.NORMALTRANSMISSION);
        }else{
            if(ClientType.IOS.equals(clientType)){
                calculationLimitRequest.setIsMessageList(AuthStatisticsConstant.CANNOTREAD);
            }else {
                calculationLimitRequest.setIsMessageList(AuthStatisticsConstant.READWITHOUTPERMISSION);
            }
        }
        //封装applist
        List<AppRecord> appRecords=appRecordRepository.findByUserId(calculationLimitRequest.getCustomerId());
        calculationLimitRequest.setApplist(appRecords);
        if(appRecords!=null&&appRecords.size()>0){
            calculationLimitRequest.setIsAppList(AuthStatisticsConstant.NORMALTRANSMISSION);
        }else{
            if(ClientType.IOS.equals(clientType)){
                calculationLimitRequest.setIsAppList(AuthStatisticsConstant.CANNOTREAD);
            }else {
                calculationLimitRequest.setIsAppList(AuthStatisticsConstant.READWITHOUTPERMISSION);
            }
        }
        //封装设备信息
        List<DeviceRecord>  deviceRecords=deviceRecordRepository.findByUserId(calculationLimitRequest.getCustomerId());
        logger.info("=======开始封装设备信息数据，大小为"+deviceRecords.size()+"===========");
        if(deviceRecords!=null&&deviceRecords.size()>0){
            calculationLimitRequest.setDeviceInfo(deviceRecords.get(0));
        }
    }



}
